import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_lib/utils/LogUtils.dart';

class NetUtils {
  static String TAG = "NetUtils";
  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  static final int CONNECR_TIME_OUT = 15 * 1000;
  static final int SEND_TIME_OUT = 15 * 1000;
  static final int RECIVE_TIME_OUT = 15 * 1000;
  var _dio = new Dio();

  NetUtils._internal() {
    initDio();
  }

  static NetUtils _httpManger = NetUtils._internal();

  factory NetUtils() {
    return _httpManger;
  }

  ///配置dio
  void initDio() {
    LogD("initDio");
    _dio = Dio();
    // 配置dio实例
    _dio.options.connectTimeout = Duration(seconds: CONNECR_TIME_OUT);
    _dio.options.sendTimeout = Duration(seconds: SEND_TIME_OUT);
    _dio.options.receiveTimeout = Duration(seconds: RECIVE_TIME_OUT);

    _dio.interceptors.add(LogInterceptor(responseBody: true));
    /// 添加拦截器
  }

  Future<Response> get(
    String url, {
    Map<String, dynamic>? queryParameters,Options? options
  }) async {
    //LogD("get url:$url");
    // LogD("queryParameters:$queryParameters");
    return _requstHttp(url, true, queryParameters);
  }

  Future<Response> post(
    String url, {
    Map<String, dynamic>? queryParameters,Options? options
  }) async {
    //LogD("post url:$url");
    // LogD("queryParameters:$queryParameters");
    return _requstHttp(url, false, queryParameters);
  }

  Future<Response> _requstHttp(String url,
      [bool isGet = true, queryParameters, bool isCancelable = true,Options? options]) async {
    CancelToken? cancelToken;
    Response response;
    if (isGet) {

      response = await _dio.get(url,options: options,
          queryParameters: queryParameters, cancelToken: cancelToken);
    } else {
      response =
          await _dio.post(url, options: options,data: queryParameters, cancelToken: cancelToken);
    }

    return response;
  }

  void LogD(String message) {
    LogUtils.d(message + "", tag: TAG);
  }
}
